package com.squid.base.config.mybatis;//package com.mytest.test.config.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 实体类自动添加创建人，创建时间，修改人和修改时间
 * @author jh
 * @date 2022/11/30 14:31
 */
@Component
@Slf4j
public class CustomizeMetaObjectHandler implements MetaObjectHandler {
    /**
     * 未登录用户默认用户名
     */
    private static final String DEFAULT_CONSTANT_USER = "NO_LOGIN_USER";


    /**
     * 添加字段时自动填充策略
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();
        String createUser;
        String updateUser;
        //获取到当前线程绑定的请求对象
        String currUsername = "admin";
        if (StringUtils.isEmpty(currUsername)) {
            createUser = DEFAULT_CONSTANT_USER;
            updateUser = DEFAULT_CONSTANT_USER;
        } else {
            createUser = currUsername;
            updateUser = currUsername;
        }
        this.setFieldValByName("createTime",date,metaObject);
        this.setFieldValByName("updateTime",date,metaObject);
        this.setFieldValByName("createUser", createUser, metaObject);
        this.setFieldValByName("updateUser", updateUser, metaObject);
        log.info("插入数据获取到当前登录人为:{}，时间为:{}", createUser, date);
    }

    /**
     * 修改字段时自动填充策略
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Date date = new Date();
        String updateUser;
        //获取到当前线程绑定的请求对象
        String currUsername = "admin";
        System.out.println(currUsername);
        if (StringUtils.isEmpty(currUsername)) {
            updateUser = DEFAULT_CONSTANT_USER;
        } else {
            updateUser = currUsername;
        }
        this.setFieldValByName("updateTime",date,metaObject);
        this.setFieldValByName("updateUser", updateUser, metaObject);
        log.info("更新数据获取到当前登录人为:{}，时间为:{}", updateUser, date);
    }
}
